import { execSync } from 'child_process';
import { readFileSync, rmSync, writeFileSync, copyFileSync, mkdirSync, renameSync } from 'fs';
import pac from './package.json' with { type: 'json' };
import { join } from 'path';
const { name } = pac;
try {
  rmSync('./build', {
    recursive: true,
    force: true
  });
  execSync('npx @vercel/ncc build src/main.ts -o build -a -m', {
    stdio: 'inherit'
  });

  writeFileSync(
    './build/index.js',
    "const{createRequire}=require('node:module');require=createRequire(__filename);" +
      readFileSync('./build/index.js', 'utf-8')
  );

  let runName = `${name}-${process.platform}-${process.arch}`;
  if (process.platform === 'win32') {
    runName += '.exe';
  }
  rmSync(`./${runName}`, {
    recursive: true,
    force: true
  });
  rmSync(`./sea-prep.blob`, {
    recursive: true,
    force: true
  });

  execSync(`node --experimental-sea-config sea-config.json`, {
    stdio: 'inherit'
  });

  copyFileSync(process.execPath, runName);

  if (process.platform === 'darwin') {
    execSync(`codesign --remove-signature ${runName}`);
  }

  execSync(
    `npx postject ${runName} NODE_SEA_BLOB sea-prep.blob --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 ${process.platform === 'darwin' ? '--macho-segment-name NODE_SEA' : ''}`
  );

  if (process.platform === 'darwin') {
    execSync(`codesign --sign - ${runName}`);
  }

  rmSync(`./dist`, {
    recursive: true,
    force: true
  });

  rmSync(`./build`, {
    recursive: true,
    force: true
  });

  rmSync(`./sea-prep.blob`, {
    recursive: true,
    force: true
  });

  mkdirSync(`./dist`);
  renameSync(`./${runName}`, join(`./dist`, runName));
  copyFileSync('./.env.example', join(`./dist`, '.env'));
} catch (e) {
  console.error(e);
}
